//
//  CYDBConfigLogic.m
//  CreditAddressBook
//
//  Created by Lee on 15/8/5.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYDBConfigLogic.h"

@implementation CYDBConfigLogic

/**
 *  当前数据库版本号，该框架将其自动保存到数据库以备下次启动检查
 *
 *  @return
 */
- (int)dbVersion {
    return 2;
}

/**
 * 第一次创建数据库时的方法。子类需要覆盖该方法，实现第一次创建数据库时的代码
 *
 * @param db FMDB的数据库对象
 * @return YES=成功，NO=失败
 */
- (BOOL)onCreate:(FMDatabase *)db {
//    CYLog(@">>> onCreate");
    
    if (!db) {
        NSAssert(0, @"db can't be null");
        return false;
    }
    
    @try {
        BOOL result = NO;
        
        result = [db executeUpdate:@"create table if not exists t_call_history (id text primary key UNIQUE not null, parentId text, status text, phone text, name text, duration INTEGER, create_time INTEGER, callHistory blob);"];
        
        if (!result) {
            CYLog(@"create table Users Failed");
            return false;
        }
        
        return [self onUpgrade:db oldVersion:DBCONFIG_FIRST_VER newVersion:self.dbVersion];
        
    }
    @catch (NSException *exception) {
        NSAssert1(0, @"Exception: %@", exception.reason);
        return false;
    }
    @finally {
        
    }
    
}

/**
 * 数据库版本增加时的方法，比如数据库表结构发生变化，要从版本v1升级到版本v2
 *
 * @param db FMDB的数据库对象
 * @param oldVersion 当期数据库的版本
 * @param newVersion 要更新的新的数据库的版本
 */
- (BOOL)onUpgrade:(FMDatabase *)db oldVersion:(int)oldVersion newVersion:(int)newVersion {
//    CYLog(@">>> onUpgrade, oldVersion=%d, newVersion=%d", oldVersion, newVersion);
    
    if (!db) {
        NSAssert(0, @"db can't be null");
        return false;
    }
    
    @try {
        BOOL rev = NO;
        for(int ver = oldVersion; ver < newVersion; ver++) {
            rev = NO;
            switch(ver) {
                case 2:
                    rev = [self upgradeVersion1To2:db];
                    break ;
                    
                default :
                    break ;
            }
            if (!rev) return false;
        }
        
        return true;
    }
    @catch (NSException *exception) {
        NSAssert1(0, @"Exception: %@", exception.reason);
        return false;
    }
    @finally {
        
    }
}

#pragma mark - Custom Method
- (BOOL)upgradeVersion1To2:(FMDatabase *)db {
    
    FMResultSet *rs = [db executeQuery:@"SELECT sql FROM sqlite_master WHERE type = 'table' AND tbl_name = 't_call_history' "];
    NSString *tabCreateSql = nil;
    BOOL tableIsExistus = NO;
    while([rs next]) {
        tableIsExistus = YES;
        tabCreateSql = [rs stringForColumnIndex:0];
        break;
    }
    [rs close];
    if (tableIsExistus && tabCreateSql) {
        NSString *column_FileName = @"callHistory";
        NSRange range1 = [tabCreateSql rangeOfString: column_FileName];
        if (range1.length < 1) {
            NSString *sql = [NSString stringWithFormat:@"ALTER TABLE t_call_history ADD %@ blob NULL; ", column_FileName];
            BOOL rev = [db executeUpdate:sql];
            if (!rev) {
                [db rollback];
                CYLog(@"执行以下sql时失败：\n%@\n失败原因是：%@", sql, [db lastErrorMessage]);
                NSAssert2(0, @"执行以下sql时失败：\n%@\n失败原因是：%@", sql, [db lastErrorMessage]);
                return false;
            }
        }
    }
    return true;
}
@end
